<%--其他出入库增加--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<head>
    <link rel="stylesheet" href="${APP_PATH}/static/layui/css/layui.css" type="text/css" />
    <link rel="stylesheet" href="${APP_PATH}/plugins/public_components/css/select2.css" />
    <%--行编辑样式--%>
    <%--<link rel="stylesheet" href="layui/css/layui.css?v=201805080202" />--%>
    <!--[if lt IE 9]>
    <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
    <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style type="text/css">
        td .layui-form-select {
            margin-top: -5px;
        }

        /*设置 layui 表格中单元格内容溢出可见样式*/
        #tableGrid_operationOther_div .layui-table-view,
        #tableGrid_operationOther_div .layui-table-box,
        #tableGrid_operationOther_div .layui-table-body {
            overflow: visible;
            padding: 0 0 0 0;
            margin: 0 0 0 0; /* 根据实际情况调整 */
        }

        #tableGrid_operationOther_div .layui-table-cell {
            height: auto;
            overflow: visible;
        }

        /*您可以将下列样式写入自己的样式表中*/
        .childBody {
            padding: 15px;
        }

        .layui-input {
            height: 30px;
        }

        /*layui 元素样式改写*/
        .layui-btn-sm {
            line-height: normal;
            font-size: 12.5px;
        }

        .layui-table-view .layui-table-body {
            min-height: 210px;
        }

        .layui-table-cell .layui-input.layui-unselect {
            height: 30px;
            line-height: 30px;
        }

        /*设置 layui 表格中单元格内容溢出可见样式*/
        .table-overlay .layui-table-view,
        .table-overlay .layui-table-box,
        .table-overlay .layui-table-body {
            overflow: visible;
        }

        .table-overlay .layui-table-cell {
            height: auto;
            overflow: visible;
        }

        /*文本对齐方式*/
        .text-center {
            text-align: center;
        }

        .layui-form-item {
            margin-bottom: 0px;
        }

        .select2-container-multi .select2-choices .select2-search-field input {
            height: 13px;
        }

    </style>
</head>
<script src="${APP_PATH}/static/layui/layui.all.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="${APP_PATH}/plugins/public_components/js/jquery-1.10.2.min.js"></script>
<script src="${APP_PATH}/plugins/public_components/js/select2.js"></script>

<div id="operationOther_edit" style="margin: 15px">
    <form class="layui-form">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 100px">业务类型</label>
                <div class="layui-input-inline">
                    <select id="businessType" lay-verify="required" lay-verType="tips" lay-filter="businessType"
                            v-model="formData.businessType" lay-search>
                        <option value="">请选择</option>
                        <option value="1">其他出库</option>
                        <option value="2">其他入库</option>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 100px">业务目的</label>
                <div class="layui-input-inline">
                    <select id="businessPurpose" lay-filter="businessPurpose" lay-verify="required" lay-verType="tips"
                            v-model="formData.businessPurpose" lay-search>
                        <option value="">请选择</option>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 100px">领用用途</label>
                <div class="layui-input-inline">
                    <select id="effect" lay-filter="effect" v-model="formData.effect" lay-search>
                        <option value="">请选择</option>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 100px">事物处理日期</label>
                <div class="layui-input-inline">
                    <input id="createTime" type="text" class="layui-input" lay-verify="required" lay-verType="tips">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 100px">厂区</label>
                <div class="layui-input-inline">
                    <select id="areaCode" lay-filter="areaCode" v-model="formData.areaCode" lay-verify="required"
                            lay-verType="tips" lay-search>
                        <option value="">请选择</option>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 100px">仓库</label>
                <div class="layui-input-inline">
                    <select id="storeCode" lay-filter="storeCode" v-model="formData.storeCode" lay-verify="required"
                            lay-verType="tips" lay-search>
                        <option value="">请选择</option>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 100px">生产厂/部门</label>
                <div class="layui-input-inline">
                    <select id="manufacturer" lay-filter="manufacturer" v-model="formData.manufacturer"
                            lay-verType="tips" lay-verify="required" lay-search>
                        <option value="">请选择</option>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 100px">工序/二级部门</label>
                <div class="layui-input-inline">
                    <select id="process" lay-filter="process" v-model="formData.process" lay-search>
                        <option value="">请选择</option>
                    </select>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 100px">机台</label>
                <div class="layui-input-inline">
                    <input type="text" name="machine" autocomplete="off" class="layui-input" v-model="formData.machine">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 100px">维修/加工单位</label>
                <div class="layui-input-inline">
                    <input type="text" name="maintainCode" autocomplete="off" class="layui-input" lay-verType="tips"
                           v-model="formData.maintainCode" lay-verify="maintainCode">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 100px">供应商</label>
                <div class="layui-input-inline">
                    <select id="supplierCode" lay-filter="supplierCode" v-model="formData.supplierCode" lay-search>
                        <option value="">请选择</option>
                    </select>
                </div>
            </div>
            <div class="layui-inline" id="carInfoDiv" style="display: none">
                <label class="layui-form-label" style="width: 100px">装车通知单</label>
                <div class="layui-input-inline">
                    <select id="carInfo" lay-filter="carInfo" v-model="formData.carInfo" lay-verType="tips"
                            lay-verify="carInfo" lay-search>
                        <option value="">请选择</option>
                    </select>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 100px">总金额</label>
                <div class="layui-input-inline">
                    <input type="text" readonly id="amount" name="amount" autocomplete="off" class="layui-input"
                           v-model="formData.amount">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 100px">备注</label>
                <div class="layui-input-inline">
                    <input type="text" name="remark" autocomplete="off" class="layui-input" v-model="formData.remark">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 100px"></label>
                <button type="submit" class="layui-btn layui-btn-sm layui-btn-checked" lay-submit=""
                        lay-filter="pushFormData">
                    <i class="layui-icon">&#xe605;</i>提交
                </button>
            </div>
        </div>
    </form>
    <%-- table grid --%>
    <div id="tableGrid_operationOther_div">
        <table id="tableGrid_operationOther" lay-filter="tableGridFilter_operationOther"></table>
    </div>
    <%-- table grid toolbar --%>
    <script type="text/html" id="tableGridToolbar_operationOther">
        <div class="">
            <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" lay-event="remove">
                <i class="layui-icon">&#xe640;</i>清除
            </button>
            <div class="layui-inline" style="margin-left: 10px;">
                <label style="width: 65px">物料编码：</label>
                <div class="layui-form layui-input-inline">
                    <%--<input type="text" id="materialCodeSelect" autocomplete="off">--%>
                    <input type="text" id="materialCodeSelect" name="materialCode"
                           style="width:350px;margin-right:10px;" />
                </div>
            </div>
            <button type="button" lay-event="insert" class="layui-btn layui-btn-sm layui-btn-normal">
                <i class="layui-icon">&#xe654;</i>添加
            </button>
        </div>
    </script>
</div>

<script>
    const context_path = '${APP_PATH}';
    const table = layui.table,
        form = layui.form,
        layer = layui.layer,
        laydate = layui.laydate,
        util = layui.util;

    let vm = new Vue({
        el: '#operationOther_edit',
        data: {
            carInfoList: [],
            locatorCodeList: [],
            formData: {
                businessType: '',
                businessPurpose: '',
                businessPurposeName: '',
                createTime: '',
                areaCode: '',
                storeCode: '',
                manufacturer: '',
                process: '',
                machine: '',
                maintainCode: '',
                amount: 0,
                effect: '',
                remark: '',
                supplierCode: '',
                supplierName: '',
                carInfo: '',
                lineList: []
            }
        },
        methods: {
            pushFormData() {
                console.info(this.formData)
                let oldData = table.cache['tableGridSet_operationOther'];
                if (oldData.length <= 0) {
                    layer.msg('请输入子表信息', { icon: 2 });
                    return;
                }
                let indexLine;
                let every = oldData.every((value, index) => {
                    indexLine = index + 1;
                    return value.locatorCode != "" && value.locatorCode != 0 && value.lotsNum != "";
                });
                if (!every) {
                    layer.msg('子表行号【' + indexLine + '】 批次号 或 库位 不能为空', { icon: 2 });
                    return;
                }
                this.formData.lineList = oldData;
                $.ajax({
                    type: 'POST',
                    url: context_path + "/ycl/operation/other/push",
                    contentType: "application/json",
                    async: false,
                    dataType: "json",
                    data: JSON.stringify(this.formData),
                    success: function (res) {
                        if (res.code == 0) {
                            layer.msg(res.msg, { icon: 1 });
                            window.parent.tableRender();
                            let index = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(index);
                        } else {
                            layer.msg(res.msg, { icon: 2 });
                        }
                    }
                })
            },
            initCreateTime() {
                this.formData.createTime = util.toDateString(new Date());
                //日期时间选择器
                laydate.render({
                    elem: '#createTime'
                    , type: 'datetime'
                    , value: this.formData.createTime
                    , done: function (value, date, endDate) {
                        vm.formData.createTime = value;
                    }
                });
            },
            initSelect(async, url, data, domId, callback) {
                let dataJson = { queryString: "", limit: 100, page: 1 };
                let json = $.extend({}, dataJson, data);
                let valueField = data.valueField || 'id',
                    textField = data.textField || 'text';
                $.ajax({
                    type: 'GET',
                    url: context_path + url,
                    data: json,
                    async: async,
                    dataType: "json",
                    success: function (res) {
                        let html = '';
                        let list = res.data;
                        if (!!callback) {
                            callback(list);
                        }
                        for (let i = 0; i < list.length; i++) {
                            html += '<option value=' + list[i][valueField] + '>' + list[i][textField] + '</option>';
                        }
                        let $id = $('#' + domId);
                        $id.empty();
                        $id.append('<option value="">请选择</option>');
                        $id.append(html);
                        form.render('select');
                    }
                });
            },
            resetSelectOptions(data, domId, settings) {
                settings = settings || {};
                let valueField = settings.valueField || 'id',
                    textField = settings.textField || 'text';
                let html = '';
                for (let i = 0; i < data.length; i++) {
                    html += '<option value=' + data[i][valueField] + '>' + data[i][textField] + '</option>';
                }
                let $id = $('#' + domId);
                $id.empty();
                $id.append('<option value="">请选择</option>');
                $id.append(html);
                form.render('select');
            },
            renderSelectOptions(data, settings) {
                settings = settings || {};
                let valueField = settings.valueField || 'id',
                    textField = settings.textField || 'text',
                    selectedValue = settings.selectedValue || "";
                let html = [];
                for (let i = 0, item; i < data.length; i++) {
                    item = data[i];
                    html.push('<option value="');
                    html.push(item[valueField]);
                    html.push('"');
                    if (selectedValue && item[valueField] == selectedValue) {
                        html.push(' selected="selected"');
                    }
                    html.push('>');
                    html.push(item[textField]);
                    html.push('</option>');
                }
                return html.join('');
            },
            initLocatorCodeList(factorycode, storeCode) {
                $.ajax({
                    type: 'get',
                    url: context_path + "/goods/getShelfByFactWareCode.do",
                    data: {
                        warehouseCode: storeCode,
                        entityId: factorycode,
                        queryString: '',
                        pageSize: 999,
                        pageNo: 1
                    },
                    async: true,
                    dataType: "json",
                    // contentType: "application/json; charset=utf-8",
                    success: function (res) {
                        vm.locatorCodeList = res.result
                    }
                });
            },
            // 业务目的
            initBusinessPurposeSelect(type) {
                this.initSelect(true, '/BaseDicType/otherTransaction/' + type, {}, 'businessPurpose');
            },
            // 厂区
            initAreaCodeSelect() {
                this.initSelect(true, '/ycl/baseinfo/basedata/area/0', {}, 'areaCode');
            },
            // 仓库
            initStoreCodeSelect(param) {
                this.initSelect(true, '/ycl/baseinfo/basedata/store/' + param, {
                    valueField: 'code',
                    textField: 'text'
                }, 'storeCode');
            },
            // 生产厂
            initManufacturerSelect(param) {
                this.initSelect(true, '/ycl/baseinfo/basedata/plant/' + param, {
                    valueField: 'value',
                    textField: 'text'
                }, 'manufacturer');
            },
            // 工序
            initProcessSelect(param) {
                this.initSelect(true, '/ycl/baseinfo/plant/op/' + param, {
                    valueField: 'code',
                    textField: 'text'
                }, 'process');
            },
            // 供货商
            initSupplierCodeSelect() {
                this.initSelect(true, '/wms2/baseinfo/organize/vendor/', {}, 'supplierCode');
            },
            // 领用用途
            initEffectSelect() {
                this.initSelect(true, '/BaseDicType/lyyt/0', {}, 'effect');
            },
            // 装车通知单
            initCarInfoSelect() {
                this.initSelect(true, '/wms2/baseinfo/warehouse/entruckNotice/0', {
                    valueField: 'num',
                    textField: 'num'
                }, 'carInfo', (list) => this.carInfoList = list);
            },
            // 重置装车通知单
            resetCarInfoSelect() {
                this.resetSelectOptions(this.carInfoList, 'carInfo', {
                    valueField: 'num',
                    textField: 'num'
                });
            },
            renderLotsNumSelectOptions: function (e) {
                let list = [];
                $.ajax({
                    type: 'GET',
                    url: context_path + '/wms2/baseinfo/inventory/lotsnum/' + vm.formData.areaCode + '/' + vm.formData.storeCode + '/' + e.materialCode,
                    async: false,
                    dataType: "json",
                    success: function (res) {
                        list = res.data;
                    }
                });

                var html = [];
                html.push('<div class="layui-form" lay-filter="lotsNum">');
                html.push('<select name="lotsNum" id="lotsNum" data-value="' + e.tempId + '" lay-filter="lotsNum" lay-search>');
                html.push('<option value="">请选择</option>');
                if (list) {
                    list.forEach(m => {
                        html.push('<option value="');
                        html.push(m.CODE);
                        html.push('"');
                        if (m.CODE == e.lotsNumStr) {
                            html.push(' selected="selected"');
                        }
                        html.push('>');
                        html.push(m.TEXT);
                        html.push('</option>');
                    })
                }
                html.push('</select></div>');
                return html.join('');
            },
            initTable() {
                //原列表集合数据
                table.render({
                    elem: '#tableGrid_operationOther'
                    , data: []
                    , page: false
                    , limit: 99999
                    , toolbar: '#tableGridToolbar_operationOther'
                    , id: "tableGridSet_operationOther"
                    , size: 'sm'
                    , height: 'full-250'
                    , defaultToolbar: []
                    , cols: [[
                        { type: 'checkbox', width: 30 }
                        , { field: 'tempId', title: '', hide: true }
                        , { type: 'numbers', field: 'lineCode', title: '行号' }
                        , { field: 'materialCode', title: '物料编码', width: 140 }
                        , { field: 'materialName', title: '物料名称', width: 250 }
                        , {
                            field: 'lotsNumStr',
                            title: '批次号',
                            width: 220,
                            templet: (d) => vm.renderLotsNumSelectOptions(d)
                        }
                        , { field: 'locatorCode', title: '库位', width: 200 }
                        , { field: 'storeQuantity', title: '库存数量', width: 80 }
                        // , {
                        //     field: 'orderQuantity', title: '订单数量', width: 100, edit: 'text',
                        //     templet: (d) => d.orderQuantity || 0
                        // }
                        , {
                            field: 'quantity', title: '数量', width: 100, edit: 'text',
                            templet: (d) => d.quantity || 0
                        }
                        , { field: 'primaryUnit', title: '单位', width: 100 }
                        , {
                            field: 'price', title: '单价', width: 100, edit: 'text',
                            templet: (d) => d.price || 0
                        }
                        , { field: 'remark', title: '备注', edit: 'text' }
                    ]]
                });
                initMaterialCodeSelect();
            },
            initTable2() {
                //原列表集合数据
                table.render({
                    elem: '#tableGrid_operationOther'
                    , data: []
                    , page: false
                    , limit: 99999
                    , toolbar: '#tableGridToolbar_operationOther'
                    , id: "tableGridSet_operationOther"
                    , size: 'sm'
                    , height: 'full-250'
                    , defaultToolbar: []
                    , cols: [[
                        { type: 'checkbox', width: 30 }
                        , { field: 'tempId', title: '', hide: true }
                        , { type: 'numbers', field: 'lineCode', title: '行号' }
                        , { field: 'materialCode', title: '物料编码', width: 140 }
                        , { field: 'materialName', title: '物料名称', width: 250 }
                        , { field: 'lotsNum', title: '批次号', width: 220, edit: 'text' }
                        // , { field: 'locatorCode', title: '库位', width: 140, edit: 'text' }
                        , {
                            field: 'locatorCode', title: '库位', width: 200, templet: function (d) {
                                let options = vm.renderSelectOptions(vm.locatorCodeList, {
                                    selectedValue: d.locatorCode,
                                    valueField: 'code',
                                    textField: 'codename'
                                });
                                return '<select name="locatorCode" lay-filter="locatorCode" lay-search><option value="0">请选择</option>' + options + '</select>';
                            }
                        }
                        // , { field: 'storeQuantity', title: '库存数量', width: 100 }
                        // , {
                        //     field: 'orderQuantity', title: '订单数量', width: 100, edit: 'text',
                        //     templet: (d) => d.orderQuantity || 0
                        // }
                        , {
                            field: 'quantity', title: '数量', width: 80, edit: 'text',
                            templet: (d) => d.quantity || 0
                        }
                        , { field: 'primaryUnit', title: '单位', width: 100 }
                        , {
                            field: 'price', title: '单价', width: 100, edit: 'text',
                            templet: (d) => d.price || 0
                        }
                        , { field: 'remark', title: '备注', edit: 'text' }
                    ]]
                });
                initMaterialCodeSelect();
            },
            calculateAmount() {
                let oldData = table.cache['tableGridSet_operationOther'];
                let amount = 0;
                for (let data of oldData) {
                    amount = amount.add(data.price.mul(data.quantity));
                }
                vm.formData.amount = amount;
                $("#amount").val(amount);
            },
            syncOrderQuantity(materialCode, value) {
                let materialCodeInput = $("#materialCodeSelect").val().trim();
                let oldData = table.cache['tableGridSet_operationOther'];
                table.reload('tableGridSet_operationOther', {
                    data: oldData.map(data => {
                        if (data.materialCode == materialCode) {
                            data.orderQuantity = value;
                        }
                        return data;
                    })
                });
                $("#materialCodeSelect").val(materialCodeInput);
            }
        },
        created() {
        },
        mounted() {
            this.initCreateTime();
            this.initAreaCodeSelect();
            this.initSupplierCodeSelect();
            // this.initManufacturerSelect();
            this.initEffectSelect();
            this.initCarInfoSelect();
            form.render('select');
            this.initTable();
            initMaterialCodeSelect();
        }
    })

    form.verify({
        maintainCode: function (value, item) { //value：表单的值、item：表单的DOM对象
            if (vm.formData.businessPurpose == 102 && !value.trim()) {
                return '必填项不能为空';
            }
        },
        carInfo: function (value, item) { //value：表单的值、item：表单的DOM对象
            if (vm.formData.businessPurpose == 102 && !value) {
                return '必填项不能为空';
            }
        }
    });

    function initMaterialCodeSelect() {
        /**选择质保号*/
        $("#materialCodeSelect").select2({
            placeholder: "请选择物料编码",//文本框的提示信息
            minimumInputLength: 0, //至少输入n个字符，才去加载数据
            allowClear: true, //是否允许用户清除文本信息
            multiple: false,
            closeOnSelect: false,
            formatNoMatches: "没有结果",
            formatSearching: "搜索中...",
            formatAjaxError: "加载出错啦！",
            ajax: {
                url: context_path + '/materials/getMaterialPageByCode',
                dataType: 'json',
                delay: 250,
                data: function (term, pageNo) { //在查询时向服务器端传输的数据
                    term = $.trim(term);
                    // selectParam = term;
                    return {
                        code: term, //联动查询的字符
                        limit: 15, //一次性加载的数据条数
                        page: pageNo //页码
                    }
                },
                results: function (data, pageNo) {
                    var res = data.data;
                    //如果没有查询到数据，将会返回空串
                    if (res.length > 0) {
                        var more = (pageNo * 15) < data.count; //用来判断是否还有更多数据可以加载
                        return {
                            results: res,
                            more: more
                        };
                    } else {
                        return {
                            results: {
                                "id": "0",
                                "text": "没有更多结果"
                            }
                        };
                    }
                },
                cache: true
            }
        });

        $("#materialCodeSelect").on("change", function (e) {
            // var datas = $("#materialCodeSelect").select2("val");
            /*selectData = datas;
            var selectSize = datas.length;
            if (selectSize > 1) {
                var $tags = $("#materialCodeSelect .select2-choices");
                //$("#s2id_materialInfor").html(selectSize+"个被选中");
                var $choicelist = $tags.find(".select2-search-choice");
                var $clonedChoice = $choicelist[0];
                $tags.children(".select2-search-choice").remove();
                $tags.prepend($clonedChoice);
                $tags.find(".select2-search-choice").find("div").html(selectSize + "个被选中");
                $tags.find(".select2-search-choice").find("a").removeAttr("tabindex");
                $tags.find(".select2-search-choice").find("a").attr("href", "#");
                $tags.find(".select2-search-choice").find("a").attr("onclick", "removeChoice();");
            }*/
            //执行select的查询方法
            // $("#materialCodeSelect").select2("search", selectParam);
        });
    }

    //监听select
    form.on('select(businessType)', function (data) {
        if (data.value == 1) {
            vm.initTable();
        } else {
            if (vm.formData.areaCode != '' && vm.formData.storeCode != '') {
                vm.initLocatorCodeList(vm.formData.areaCode, vm.formData.storeCode);
            }
            vm.initTable2();
        }
        vm.formData.businessType = data.value;
        vm.formData.businessPurpose = "";
        vm.formData.businessPurposeName = "";
        if (!!data.value) {
            vm.initBusinessPurposeSelect(data.value);
        } else {
            vm.resetSelectOptions([], 'businessPurpose', {});
        }
    });
    form.on('select(businessPurpose)', function (data) {
        vm.formData.businessPurpose = data.value;
        vm.formData.businessPurposeName = data.elem[data.elem.selectedIndex].text;
        vm.formData.carInfo = "";
        if (data.value == 102) {
            $("#carInfoDiv").show();
            vm.resetCarInfoSelect();
        } else {
            $("#carInfoDiv").hide();
        }
    });
    form.on('select(areaCode)', function (data) {
        vm.formData.areaCode = data.value;
        vm.formData.storeCode = "";
        vm.formData.manufacturer = "";
        if (!!data.value) {
            vm.initStoreCodeSelect(data.value);
            vm.initManufacturerSelect(data.value);
        } else {
            vm.resetSelectOptions([], 'storeCode', {});
            vm.resetSelectOptions([], 'manufacturer', {});
        }
    });
    form.on('select(storeCode)', function (data) {
        if (vm.formData.businessType == "") {
            layer.msg('请选择业务类型', { icon: 2 });
            vm.initStoreCodeSelect(vm.formData.areaCode);
            return;
        }
        vm.formData.storeCode = data.value;
        if (vm.formData.businessType == 1) {
            vm.initTable();
        } else {
            vm.initLocatorCodeList(vm.formData.areaCode, vm.formData.storeCode);
            vm.initTable2();
        }
    });
    form.on('select(manufacturer)', function (data) {
        vm.formData.manufacturer = data.value;
        vm.formData.process = "";
        if (!!data.value) {
            vm.initProcessSelect(data.value);
        } else {
            vm.resetSelectOptions([], 'process', {});
        }
    });
    form.on('select(process)', function (data) {
        vm.formData.process = data.value;
    });
    form.on('select(effect)', function (data) {
        vm.formData.effect = data.value;
    });
    form.on('select(supplierCode)', function (data) {
        if (!!data.value) {
            vm.formData.supplierCode = data.value;
            vm.formData.supplierName = data.elem[data.elem.selectedIndex].text;
        } else {
            vm.formData.supplierCode = "";
            vm.formData.supplierName = "";
        }
    });
    form.on('select(carInfo)', function (data) {
        vm.formData.carInfo = data.value;
    });

    //监听select
    form.on('select(lotsNum)', function (data) {
        let elem = data.othis.parents('tr');
        let id = elem.first().find('td').eq(1).text();
        let oldData = table.cache['tableGridSet_operationOther'];
        let temp = data.value.split(',');
        oldData.forEach(n => {
            if (n.tempId == id) {
                n.lotsNumStr = data.value;
                n.lotsNum = temp[0];
                n.locatorCode = temp[1];
                n.storeQuantity = temp[2];
            }
        })
        table.reload('tableGridSet_operationOther', {
            data: oldData
        })
        initMaterialCodeSelect();
    });

    form.on('select(locatorCode)', function (data) {
        let elem = $(data.elem);
        let trElem = elem.parents('tr');
        let tableData = table.cache['tableGridSet_operationOther'];
        // 更新到表格的缓存数据中，才能在获得选中行等等其他的方法中得到更新之后的值
        tableData[trElem.data('index')][elem.attr('name')] = data.value;
    });

    //请勾选
    table.on('toolbar(tableGridFilter_operationOther)', function (obj) {
            let materialCode = $("#materialCodeSelect").val().trim();
            switch (obj.event) {
                case 'insert': // 增行
                    if (vm.formData.businessType == "") {
                        layer.msg('请选择业务类型', { icon: 2 });
                        return;
                    }
                    if (vm.formData.areaCode == "") {
                        layer.msg('请选择厂区', { icon: 2 });
                        return;
                    }
                    if (vm.formData.storeCode == "") {
                        layer.msg('请选择仓库', { icon: 2 });
                        return;
                    }
                    if (materialCode == "") {
                        layer.msg('请输入物料编码', { icon: 2 });
                        return;
                    }
                    $.get(context_path + '/materials/code/' + materialCode, {}, function (res) {
                        let data = res.data;
                        if (data == "") {
                            layer.msg('查询不到数据', { icon: 2 });
                            return;
                        }
                        let oldData = table.cache['tableGridSet_operationOther'];
                        let tempData = oldData.filter(data => data.materialCode == materialCode);
                        let objectData = [{
                            tempId: new Date().valueOf()
                            , materialCode: data.CODE
                            , materialName: data.NAME
                            , locatorCode: ""
                            , lotsNumStr: ""
                            , lotsNum: ""
                            // , orderQuantity: tempData.length > 0 ? tempData[0].orderQuantity : 0
                            , quantity: 0
                            , primaryUnit: data.PRIMARYUNIT
                            , price: 0
                            , remark: ""
                        }];
                        table.reload('tableGridSet_operationOther', {
                            data: [...objectData, ...oldData]
                        });
                        // $("#materialCodeSelect").val(materialCode);
                        initMaterialCodeSelect();
                    })
                    break;
                case 'remove':
                    const selectData = table.checkStatus(obj.config.id).data;
                    let length = selectData.length;
                    if (length == 0) {
                        layer.msg('请选择行数据', { icon: 2 });
                        return;
                    }

                    let oldData = table.cache['tableGridSet_operationOther'];
                    for (let data of selectData) {
                        for (let i = 0; i < oldData.length; i++) {
                            if (oldData[i].tempId === data.tempId) {
                                oldData.splice(i, 1);
                                break;
                            }
                        }
                    }
                    table.reload('tableGridSet_operationOther', {
                        data: oldData
                    });
                    // $("#materialCodeSelect").val(materialCode);
                    initMaterialCodeSelect();
                    vm.calculateAmount();
                    break;
            }
        }
    );

    // 监听编辑单元格
    table.on('edit(tableGridFilter_operationOther)', function (obj) { //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
        let value = obj.value;
        let field1 = obj.field;
        if (field1 == "orderQuantity" || field1 == "quantity" || field1 == "price") {
            value = parseFloat(value);
            if (isNaN(value)) {
                value = 0;
            }
        }
        obj.update({ [field1]: value });
        let materialCode = $("#materialCodeSelect").val().trim();
        table.reload('tableGridSet_operationOther', {
            data: table.cache['tableGridSet_operationOther']
        });
        // $("#materialCodeSelect").val(materialCode);
        initMaterialCodeSelect();
        vm.calculateAmount();
        // if (field1 == "orderQuantity") {
        //     vm.syncOrderQuantity(obj.data.materialCode, value);
        // }
    });

    //监听提交
    form.on('submit(pushFormData)', function (data) {
        vm.pushFormData();
        return false;
    });

    //加法函数
    function accAdd(arg1, arg2) {
        var r1, r2, m;
        try {
            r1 = arg1.toString().split(".")[1].length;
        } catch (e) {
            r1 = 0;
        }
        try {
            r2 = arg2.toString().split(".")[1].length;
        } catch (e) {
            r2 = 0;
        }
        m = Math.pow(10, Math.max(r1, r2));
        return (arg1 * m + arg2 * m) / m;
    }

    //给Number类型增加一个add方法，，使用时直接用 .add 即可完成计算。
    Number.prototype.add = function (arg) {
        return accAdd(arg, this);
    };

    //减法函数
    function Subtr(arg1, arg2) {
        var r1, r2, m, n;
        try {
            r1 = arg1.toString().split(".")[1].length;
        } catch (e) {
            r1 = 0;
        }
        try {
            r2 = arg2.toString().split(".")[1].length;
        } catch (e) {
            r2 = 0;
        }
        m = Math.pow(10, Math.max(r1, r2));
        //last modify by deeka
        //动态控制精度长度
        n = (r1 >= r2) ? r1 : r2;
        return ((arg1 * m - arg2 * m) / m).toFixed(n);
    }

    //给Number类型增加一个add方法，，使用时直接用 .sub 即可完成计算。
    Number.prototype.sub = function (arg) {
        return Subtr(this, arg);
    };

    //乘法函数
    function accMul(arg1, arg2) {
        var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
        try {
            m += s1.split(".")[1].length;
        } catch (e) {
        }
        try {
            m += s2.split(".")[1].length;
        } catch (e) {
        }
        return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
    }

    //给Number类型增加一个mul方法，使用时直接用 .mul 即可完成计算。
    Number.prototype.mul = function (arg) {
        return accMul(arg, this);
    };

    //除法函数
    function accDiv(arg1, arg2) {
        var t1 = 0, t2 = 0, r1, r2;
        try {
            t1 = arg1.toString().split(".")[1].length;
        } catch (e) {
        }
        try {
            t2 = arg2.toString().split(".")[1].length;
        } catch (e) {
        }
        with (Math) {
            r1 = Number(arg1.toString().replace(".", ""));
            r2 = Number(arg2.toString().replace(".", ""));
            return (r1 / r2) * pow(10, t2 - t1);
        }
    }

    //给Number类型增加一个div方法，，使用时直接用 .div 即可完成计算。
    Number.prototype.div = function (arg) {
        return accDiv(this, arg);
    };

</script>
